﻿/*
 ***************************************************************************
 * Microsoft Visual C# .NET
 * 名称：       App_Input_HealthVisitPlanFinForm
 * 类型：       控制层
 * 功能说明：   健康管家-家访计划完成页面
 * 作者：       黄鑫
 * 创建日期：   2007/09/13
 * 修改日期     修改者      修改内容
 * 
 * 
 * ---
 ***************************************************************************
*/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Shpm.System.Validator;
using Shpm.System.Web.Control;
using log4net;
using Shpm.App.Input.Bean;
using Shpm.App.Input.Dao;
using Shpm.App.Commons.Db.Beans.Master;
using Shpm.System;
using Shpm.App.Commons.Utils;

public partial class App_Input_HealthVisitPlanFinForm : System.Web.UI.Page
{
    // log
    protected static ILog log = LogManager.GetLogger(typeof(App_Input_HealthVisitPlanFinForm));


    // page load
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // 取得当前登录的医生id信息
            SysUserManager manager = new SysUserManager(Context);
            SysUserBean sysUserBean = manager.getSysUserBean();
            MstSysUserBean mstSysUserBean =
                sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
            MstEmployeeBean mstEmpBean =
                sysUserBean == null ? null : sysUserBean.getEmployeeBean();
            string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
            string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;
            string emplyRole = mstEmpBean == null ? "" : mstEmpBean.Role;
            string emplyJob = mstEmpBean == null ? "" : mstEmpBean.EmployeeJob;
            string emplyLevel = mstEmpBean == null ? "" : mstEmpBean.EmployeeLevel;

            ViewState["DOCTOR_ID"] = emplyId;
            ViewState["EMPLY_LEVEL"] = emplyLevel;

            // 接收传递参数为分页编号
            if (Context.Items.Contains("ParamPageIndex1"))
            {
                ViewState["ParamPageIndex"] = Context.Items["ParamPageIndex"];
                ViewState["ParamPageIndex1"] = Context.Items["ParamPageIndex1"];
            }

            if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["VISITING_ID"])))
            {
                ViewState["VISITING_ID"] = Convert.ToString(Context.Items["VISITING_ID"]);
                ViewState["FLG"] = "0"; 
            }
            else
            {
                ViewState["VISITING_ID"] = Convert.ToString(Request.QueryString["VISITING_ID"]);
                ViewState["FLG"] = "1";       
            }
            
            ViewState["MEMBER_NO"] = Convert.ToString(Context.Items["MEMBER_NO"]);

            // 初始化控件
            initPageControls();
            bindSelectData(Convert.ToString(ViewState["VISITING_ID"]));         
        }
        
    }

    // 登记按钮
    protected void btnOk_Click(object sender, EventArgs e)
    {
        try
        {
            // do validate check
            ComValidateChecker vd = new ComValidateChecker();
            vd.CheckItems.Add(new CheckRequired(txtFactDate.Text, new ComMessage("E0094", "实际家访日期")));

            vd.CheckItems.Add(new CheckDate(txtNextDate.Text,"yyyy/MM/dd", new ComMessage("E0037", "下次家访日期")));
            vd.CheckItems.Add(new CheckDate(txtFactDate.Text, "yyyy/MM/dd", new ComMessage("E0037", "实际家访日期")));
            vd.CheckItems.Add(new CheckDateRange(DateUtils.convertToString(DateTime.Today), Convert.ToString(txtNextDate.Text),  new ComMessage("E0330", new string[] { "下次家访日期", "今天" })));
            vd.CheckItems.Add(new CheckDateRange(Convert.ToString(txtFactDate.Text), DateUtils.convertToString(DateTime.Today), new ComMessage("E0331", new string[] { "实际家访日期", "今天" })));

            if (!vd.DoValidator())
            {
                ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
                return;
            }

            // do insert update
            HealthVisitPlanDao dao = new HealthVisitPlanDao();
            HealthVisitPlanBean bean = new HealthVisitPlanBean();

            if (string.IsNullOrEmpty(Convert.ToString(ViewState["VISITING_ID"])))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "家访计划");
                return;
            }
            else
            {
                // 更新
                bean.VisitingId = Convert.ToInt32(ViewState["VISITING_ID"]);

                //Check该计划是否已经完成
                bean.VisitingFlg = true;
                bean.CancelFlg = false;
                IList lstResult = dao.ChkResult(bean);
                if (lstResult.Count != 0)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0006").ToString().Replace("{0}", "家访计划");
                    return;
                }

                //Check该计划是否已经取消
                bean.VisitingFlg = false;
                bean.CancelFlg = true;
                lstResult = dao.ChkResult(bean);
                if (lstResult.Count != 0)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0007").ToString().Replace("{0}", "家访计划");
                    return;
                }

                // update
                bean.FactDate = DateUtils.convertToDate(txtFactDate.Text);
                bean.FactTime = lstFactTime.Text;
                bean.Advice = txtAdvice.Text;
                bean.Conclusion = txtConclusion.Text;
                bean.UserId = Convert.ToString(ViewState["DOCTOR_ID"]);
                dao.UpdateResult(bean);

                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0002").ToString();
                lblEditCount.Text = Convert.ToString(Convert.ToInt32(lblEditCount.Text) + 1);
            }
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }


    }


    // 返回按钮
    protected void btnBack_Click(object sender, EventArgs e)
    {
        string url = "~/App/Input/HealthVisitPlanDetailSrhForm.aspx";
        Context.Items["ParamPageIndex1"] = ViewState["ParamPageIndex1"];
        Context.Items["MEMBER_NO"] = ViewState["MEMBER_NO"];
        ControllerUtils.Transfer(Context, url, true);
    }

    // bind data to controls
    private void bindSelectData(string visitingId)
    {
        HealthVisitPlanDao dao = new HealthVisitPlanDao();
        HealthVisitPlanBean bean = new HealthVisitPlanBean();

        if (!string.IsNullOrEmpty(Convert.ToString(visitingId)))
        {
            // get data
            bean.VisitingId = Convert.ToInt32(visitingId);
            bean.EmployeeLevel = "1";
            bean.SearchFlg = false;
            bean.EditFlg = false;
            bean = dao.Find(bean);
            if (bean != null)
            {
                ViewState["VISITING_TYPE"] = bean.VisitingType;
                lblDocId.Text = bean.DoctorId;
                lblMemId.Text = bean.MemberNo;
                lblMemName.Text = bean.MemberName;
                lblMemSex.Text = bean.MemberSex;
                lblMemTel.Text = bean.MemberTel;
                lblRoomId.Text = bean.ApartmentNo;
                lblVisitingType.Text = bean.VisitingTypeC;
                lblVisitingLevel.Text = bean.VisitingLevelC;
                lblBespokeDate.Text = DateUtils.convertToString(bean.BespokeDate.Value);
                lblBespokeTime.Text = bean.BespokeTime;
                txtFactDate.Text = bean.FactDate == null ? DateUtils.convertToString(bean.BespokeDate.Value) : DateUtils.convertToString(bean.FactDate.Value);
                lstFactTime.SelectedValue = bean.FactTime == null ? bean.BespokeTime : bean.FactTime;
                lblFrequency.Text = Convert.ToString(bean.Frequency );
                txtMemo.Text = bean.Memo;
                txtAdvice.Text = bean.Advice;
                txtConclusion.Text = bean.Conclusion;
                txtSuperiorOpinion.Text = bean.SuperiorOpinion;
                lblEditCount.Text = Convert.ToString(bean.EditCount);
                txtNextDate.Text = DateUtils.convertToString(bean.BespokeDate.Value.AddDays(bean.Frequency));


               
                return;
            }
        }
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "家访计划");
        }
    }

    // bind common catalog data 
    private void initPageControls()
    {

        HealthVisitPlanDao dao = new HealthVisitPlanDao();
        CommonDictionaryBean beanComDict = new CommonDictionaryBean();
        IList lstCat = null;

        // 家访类型
        log.Fatal("\n ***** get SUPERIOR_DOCTOR.LIMIT catalog *****");
        beanComDict.Catalog = "SUPERIOR_DOCTOR.LIMIT";
        lstCat = dao.FindByCatalog(beanComDict);
        if (lstCat.Count == 0)
        {
            ViewState["SUPERIOR_LIMIT"] = "0";
        }
        else
        {
            ViewState["SUPERIOR_LIMIT"] = Convert.ToString(((CommonDictionaryBean)lstCat[0]).Content);
        }
        // 实际访问时间
        lstFactTime.Items.Clear();
        for (int i = 1; i <= 24; i++)
        {
            string strTime;
            string strText;
            string strValue;

            if ((i + 8) < 10)
            {
                strTime = "0" + (i + 8) + ":00";
            }
            else
            {
                strTime = ((i + 8) % 24) + ":00";
            }
            strText = strTime;
            strValue = Convert.ToString((i + 8) % 24);
            ListItem item = new ListItem(strText, strText);
            lstFactTime.Items.Add(item);
        }

        // 下次访问时间
        lstNextTime.Items.Clear();
        for (int i = 1; i <= 24; i++)
        {
            string strTime;
            string strText;
            string strValue;

            if ((i + 8) < 10)
            {
                strTime = "0" + (i + 8) + ":00";
            }
            else
            {
                strTime = ((i + 8) % 24) + ":00";
            }
            strText = strTime;
            strValue = Convert.ToString((i + 8) % 24);
            ListItem item = new ListItem(strText, strText);
            lstNextTime.Items.Add(item);
        }

    }

    // bind db data to selected controls
    private void bindDataToListControl(string ControlId, IList LstData)
    {
        if (LstData == null || LstData.Count == 0) return;

        foreach (CommonDictionaryBean bean in LstData)
        {
            if (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is DropDownList)
            {
                ((DropDownList)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
            else if ((this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is CheckBoxList)
                || (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is RadioButtonList))
            {
                ((ListControl)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
        }
    }

    // before render
    void Page_PreRender(object sender, EventArgs e)
    {
        btnSuperior.Enabled = false;
        if (!string.IsNullOrEmpty(Convert.ToString(ViewState["VISITING_ID"])))
        {
            btnSuperior.Enabled = true;
        }
        if (Convert.ToString(getJobLevel()) != "0")
        {
            txtSuperiorOpinion.ReadOnly = false;
            btnSuperior.Enabled = true;
            btnOk.Enabled = true;
            btnFin.Enabled = true;
        }
        else
        {
            txtSuperiorOpinion.ReadOnly = true;
            btnSuperior.Enabled = false;
            btnOk.Enabled = true;
            btnFin.Enabled = true;
        }

        if ("1".Equals(Convert.ToString(ViewState["FLG"]))) 
        {
            btnSuperior.Enabled = false;
            btnOk.Enabled = false;
            btnFin.Enabled = false;
            btnBack.Enabled = false;
        }  
    }

    protected void btnFin_Click(object sender, EventArgs e)
    {
        try
        {
            // do validate check
            ComValidateChecker vd = new ComValidateChecker();
            vd.CheckItems.Add(new CheckRequired(txtFactDate.Text, new ComMessage("E0094", "实际家访日期")));

            vd.CheckItems.Add(new CheckDate(txtNextDate.Text, "yyyy/MM/dd", new ComMessage("E0037", "下次家访日期")));
            vd.CheckItems.Add(new CheckDate(txtFactDate.Text, "yyyy/MM/dd", new ComMessage("E0037", "实际家访日期")));
            vd.CheckItems.Add(new CheckDateRange(DateUtils.convertToString(DateTime.Today), Convert.ToString(txtNextDate.Text), "yyyy/MM/dd", new ComMessage("E0330", new string[] { "下次家访日期", "今天" })));
            vd.CheckItems.Add(new CheckDateRange(Convert.ToString(txtFactDate.Text), DateUtils.convertToString(DateTime.Today), "yyyy/MM/dd", new ComMessage("E0331", new string[] { "实际家访日期", "今天" })));

            if (!vd.DoValidator())
            {
                ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
                return;
            }

            // do insert update
            HealthVisitPlanDao dao = new HealthVisitPlanDao();
            HealthVisitPlanBean bean = new HealthVisitPlanBean();

            if (string.IsNullOrEmpty(Convert.ToString(ViewState["VISITING_ID"])))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "家访计划");
                return;
            }
            else
            {
                // 完成
                bean.VisitingId = Convert.ToInt32(ViewState["VISITING_ID"]);

                //Check该计划是否已经完成
                bean.VisitingFlg = true;
                bean.CancelFlg = false;
                IList lstResult = dao.ChkResult(bean);
                if (lstResult.Count != 0)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0006").ToString().Replace("{0}", "家访计划");
                    return;
                }

                //Check该计划是否已经取消
                bean.VisitingFlg = false;
                bean.CancelFlg = true;
                lstResult = dao.ChkResult(bean);
                if (lstResult.Count != 0)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0007").ToString().Replace("{0}", "家访计划");
                    return;
                }

                // update
                bean.FactDate = DateUtils.convertToDate(txtFactDate.Text);
                bean.FactTime = lstFactTime.Text;
                bean.Advice = txtAdvice.Text;
                bean.Conclusion = txtConclusion.Text;
                bean.MemberNo = lblMemId.Text;
                bean.DoctorId = lblDocId.Text;
                bean.VisitingType = "0";
                bean.VisitingLevel = "0";
                bean.BespokeDate = DateUtils.convertToDate(txtNextDate.Text);
                bean.BespokeTime = lstNextTime.SelectedValue;
                bean.Memo = null;
                bean.UserId = Convert.ToString(ViewState["DOCTOR_ID"]);
                if(Convert.ToString(ViewState["VISITING_TYPE"]) == "0" )
                {
                    dao.FinishPlan(bean, bean);
                }
                else
                {
                    dao.FinishPlan(bean,null);
                }

                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0020").ToString();
                lblEditCount.Text = Convert.ToString(Convert.ToInt32(lblEditCount.Text) + 1);
            }
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }

    }
    protected void btnSuperior_Click(object sender, EventArgs e)
    {

        try
        {
            // do validate check
            ComValidateChecker vd = new ComValidateChecker();
            if (!vd.DoValidator())
            {
                ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
                return;
            }

            // do insert update
            HealthVisitPlanDao dao = new HealthVisitPlanDao();
            HealthVisitPlanBean bean = new HealthVisitPlanBean();

            if (string.IsNullOrEmpty(Convert.ToString(ViewState["VISITING_ID"])))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "家访计划");
                return;
            }
            else
            {
                // 上级意见
                bean.VisitingId = Convert.ToInt32(ViewState["VISITING_ID"]);

                //Check该计划是否已经超过监管期
                bean.VisitingFlg = false;
                bean.CancelFlg = false;
                bean.SuperiorLimit = Convert.ToInt32(ViewState["SUPERIOR_LIMIT"]);
                IList lstResult = dao.ChkResult(bean);
                if (lstResult.Count != 0)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0008").ToString().Replace("{0}", "家访计划");
                    return;
                }

                //Check该计划是否已经取消
                bean.VisitingFlg = false;
                bean.CancelFlg = true;
                lstResult = dao.ChkResult(bean);
                if (lstResult.Count != 0)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0007").ToString().Replace("{0}", "家访计划");
                    return;
                }

                // update
                bean.SuperiorOpinion = txtSuperiorOpinion.Text;
                bean.UserId = Convert.ToString(ViewState["DOCTOR_ID"]);
                dao.UpdateSuperiorOpinion(bean);
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0002").ToString();
            }
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }

    }
    protected void btnFood_Click(object sender, EventArgs e)
    {
        string url = "~/App/Input/HealthDietAdviceForm.aspx";
        Context.Items["ParamPageIndex1"] = ViewState["ParamPageIndex1"];
        Context.Items["VISITING_ID"] = ViewState["VISITING_ID"];
        ControllerUtils.Transfer(Context, url, true);
    }
    protected void btnDisease_Click(object sender, EventArgs e)
    {

    }

    // 取得职员权限
    private int getJobLevel()
    {
        SysUserManager manager = new SysUserManager(Context);
        SysUserBean sysUserBean = manager.getSysUserBean();
        MstSysUserBean mstSysUserBean =
            sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
        MstEmployeeBean mstEmpBean =
            sysUserBean == null ? null : sysUserBean.getEmployeeBean();
        string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
        string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;
        PersonEmployeeBean beanEmp = new PersonEmployeeBean();
        HealthTherapyDao dao = new HealthTherapyDao();
        beanEmp.EmployeeId = emplyId;
        beanEmp = dao.GetEmployeeJob(beanEmp);
        if (beanEmp == null || string.IsNullOrEmpty(beanEmp.JobLimit))
        { return 0; }
        return Convert.ToInt32(beanEmp.JobLimit);
    }
}
